package org.mq.mymq.nameserver.store;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ReplicationChannelManager
 * @Description
 * @Author jiarong_ye
 * @Date 2025/6/20 12:04
 * @Version 1.0
 */
public class ReplicationChannelManager {
    private static Map<String, ChannelHandlerContext> channelHandlerContextMap = new HashMap<String, ChannelHandlerContext>();

    public void put(String reqId, ChannelHandlerContext ctx) {
        channelHandlerContextMap.put(reqId, ctx);
    }

    public ChannelHandlerContext get(String reqId) {
        return channelHandlerContextMap.get(reqId);
    }

    public static Map<String, ChannelHandlerContext> getChannelHandlerContextMap() {
        return channelHandlerContextMap;
    }

    /**
     * 返回有效连接
     * @return
     */
    public Map<String, ChannelHandlerContext> getValidSlaveChannelMap() {
        List<String> inValidChannelReqIdList = new ArrayList<String>();
        for (String reqId : channelHandlerContextMap.keySet()) {
            Channel channel = channelHandlerContextMap.get(reqId).channel();
            if (!channel.isActive()) {
                inValidChannelReqIdList.add(reqId);
            }
        }
        if (!inValidChannelReqIdList.isEmpty()) {
            for (String reqId : inValidChannelReqIdList) {
                channelHandlerContextMap.remove(reqId);
            }
        }
        return channelHandlerContextMap;
    }
}
